package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.ScreenUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.VehicleActivityTravelDetailBinding;
import com.qbw.app.manager.MapManager;
import com.qbw.app.model.Travel;
import com.qbw.app.model.TravelGps;
import com.qbw.app.model.Vehicle;
import com.qbw.app.model.Warning;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.home.holder.HomeTravelHolder;
import com.qbw.app.module.vehicle.holder.VehicleTravelDetailMapHolder;
import com.qbw.app.module.vehicle.holder.VehicleTravelSpeedChartHolder;
import com.qbw.app.request.impl.VehicleRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.qbw.app.module.home.holder.HomeTravelHolder.IN_TRAVEL_DETAIL;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_TRAVEL_DETAIL;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_TRAVEL_GPS;

/**
 * @author QBW
 * @date 2019-09-05
 */
public class VehicleTravelDetailActivity extends CommonActivity<VehicleActivityTravelDetailBinding> implements VehicleTravelDetailMapHolder.Listener, View.OnClickListener, HomeTravelHolder.Listener, SeekBar.OnSeekBarChangeListener {

    private final int DURATION_ONE_GPS = 300;
    private Handler mHandler = new Handler();
    private Travel mTravel;
    //private VehicleAdapter mAdapter;
    private VehicleTravelDetailMapHolder mMapHolder;
    private VehicleTravelSpeedChartHolder mChartHolder;
    private HomeTravelHolder mTravelHolder;
    private boolean mExpand;
    //private VehicleTravelDetailMapHolder mMapFullHolder;
    private VehicleTravelSpeedChartHolder mChartFullHolder;
    private int mCurrentGpsProgress = 0;
    private TravelGps.Response mTravelGpsResponse;
    private TravelGps.Response mTravelGpsResponse_adsorbent;
    private boolean isAdsorbent = false; // 道路吸附开关
    private Timer timer = new Timer();

    public static void startActivity(Context context, Travel travel) {
        Intent intent = new Intent(context, VehicleTravelDetailActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_TRAVEL, travel);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_travel_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mTravel = (Travel) args.getSerializable(Constant.KEY_TRAVEL);
        mBinding.title.setListener(this);
        mBinding.title.setSubTitleVisible(true);

        /*mBinding.rcv.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rcv.addItemDecoration(new InnerDecoration());
        mAdapter = new VehicleAdapter(this, this);
        mBinding.rcv.setAdapter(mAdapter);*/
        /*mAdapter.addChild(new ViewType(VT_TRAVEL_SPEED_CHART));
        mAdapter.addChild(new Travel());*/
        mMapHolder = new VehicleTravelDetailMapHolder(this, mBinding.map);
        mMapHolder.getBinding().ivScale.setOnClickListener(this);
        mMapHolder.getBinding().ivAdsorbent.setOnClickListener(this);
        mMapHolder.getBinding().containerMap.setTargetViewGroup(mBinding.nsvContent);
        mChartHolder = new VehicleTravelSpeedChartHolder(this, mBinding.chart);
        mChartHolder.getBinding().sb.setOnSeekBarChangeListener(this);
        mChartHolder.getBinding().ivPlay.setOnClickListener(this);
        mTravelHolder = new HomeTravelHolder(this, mBinding.travel, this);

        //mMapFullHolder = new VehicleTravelDetailMapHolder(this, mBinding.mapFull);
        //mMapFullHolder.getBinding().ivScale.setVisibility(View.GONE);
        mChartFullHolder = new VehicleTravelSpeedChartHolder(this, mBinding.chartFull);
        mBinding.chartFull.getRoot().setBackgroundResource(R.drawable.bg_e52b333c_r12);
        mChartFullHolder.getBinding().sb.setOnSeekBarChangeListener(this);
        mChartFullHolder.getBinding().ivPlay.setOnClickListener(this);

        showLoadingDialog("");
        mGeneralManager.getRequestManager()
                       .getVehicleRequest()
                       .getTravelDetail(mTravel.getTravelCode(), this)
                       .execute();

        // 后台控制道路吸附开关
        boolean showAdsorbent = mTravel.getVehicle() != null && mTravel.getVehicle().hasMenuId(Vehicle.MENU_ID_ADSORBENT);
        mMapHolder.getBinding().ivAdsorbent.setVisibility(showAdsorbent ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_TRAVEL_DETAIL)) {
            closeLoadingDialog();
            Travel.Response response = (Travel.Response) entity;
            mTravelHolder.bindData(0, response.getData());
            mBinding.title.setSubTitle(response.getData().getVehicleNick());
            mGeneralManager.getRequestManager()
                    .getVehicleRequest()
                    .getTravelGps(mTravel.getTravelCode(), isAdsorbent ? "1" : "0",this)
                    .execute();
            modelGpsData = buildGpsData(response.getData());
        } else if (method.equals(METHOD_TRAVEL_GPS)) {
            TravelGps.Response response = (TravelGps.Response) entity;
            if(isAdsorbent) {
                // 道路吸附结果处理 失败
                if(response.getData() == null || response.getData().size() <= 0) {
                    updateAdsorbent();
                    updateGpsDraw(mTravelGpsResponse);
                } else {
                    mTravelGpsResponse_adsorbent = response;
                    updateGpsDraw(mTravelGpsResponse_adsorbent);
                }
            } else {
                if((response.getData() == null || response.getData().size() <= 0) && modelGpsData != null) { // 模拟数据
                    response.setData(modelGpsData);
                }
                mTravelGpsResponse = response;
                updateGpsDraw(mTravelGpsResponse);
            }
            closeLoadingDialog();
        } else if (method.equals(VehicleRequest.METHOD_TRAVEL_ALRAMS)) {
            Warning.ResponseList res = (Warning.ResponseList) entity;
            mMapHolder.updateAlarm(res);
            //mMapFullHolder.updateAlarm(res);

            //不写下面的两行代码，在没有点击全屏的情况下，地图里面点击marker收不到点击事件
            /*onClick(mMapHolder.getBinding().ivScale);
            mHandler.post(() -> {
                onClick(mMapHolder.getBinding().ivScale);
                mBinding.cover.setVisibility(View.GONE);
            });*/
        }
    }

    /**
     * 更新轨迹绘画
     * @param response
     */
    private void updateGpsDraw(TravelGps.Response response) {
        mMapHolder.bindData(0, new VehicleTravelDetailMapHolder.Data(response.getData()));
        mChartHolder.bindData(0, new VehicleTravelSpeedChartHolder.Data(response.getData()));
        //mMapFullHolder.bindData(0, new VehicleTravelDetailMapHolder.Data(response.getData()));
        mChartFullHolder.bindData(0,
                new VehicleTravelSpeedChartHolder.Data(response.getData()));

        mGeneralManager.getRequestManager()
                .getVehicleRequest()
                .getTravelAlarms(mTravel.getTravelCode(), this)
                .execute();
    }

    /**
     * 20200205 接口不肯修改，产品又要实现，故需要客户端自己弄点假数据，把行程详情的一些些组拼到gps点上以实现模拟效果
     */
    private List<TravelGps> modelGpsData = null;
    private List<TravelGps> buildGpsData(Travel mTravel) {
        if(mTravel != null) {
            List<TravelGps> mTravelGpsList = new ArrayList<>();
            Travel.Point sPoint = mTravel.getStartPoint();
            Travel.Point ePoint = mTravel.getEndPoint();
            if(ePoint != null && ePoint.isPointValid()) { // 序列倒置
                TravelGps mTravelGps = new TravelGps();
                mTravelGps.setLatitude(ePoint.getLatitude());
                mTravelGps.setLongitude(ePoint.getLongitude());
                mTravelGps.setGpsSpeed(0d);
                mTravelGps.setGpsTime(ePoint.getTime());
                mTravelGpsList.add(mTravelGps);
            }
            if(sPoint != null && sPoint.isPointValid()) {
                TravelGps mTravelGps = new TravelGps();
                mTravelGps.setLatitude(sPoint.getLatitude());
                mTravelGps.setLongitude(sPoint.getLongitude());
                mTravelGps.setGpsSpeed(0d);
                mTravelGps.setGpsTime(sPoint.getTime());
                mTravelGpsList.add(mTravelGps);
            }
            if(mTravelGpsList != null && mTravelGpsList.size() > 0) {
                Gps gpsAfterConverted;
                if (MapManager.getInstance().isUseBaidu()) {
                    for (TravelGps gps : mTravelGpsList) {
                        gpsAfterConverted = PositionUtil.gps84_to_bd09_byBaiduSdk(
                                gps.getLatitude(),
                                gps.getLongitude());
                        gps.setLatitude(gpsAfterConverted.getWgLat());
                        gps.setLongitude(gpsAfterConverted.getWgLon());
                    }
                } else {
                    for (TravelGps gps : mTravelGpsList) {
                        gpsAfterConverted = PositionUtil.gps84_To_Gcj02(
                                gps.getLatitude(),
                                gps.getLongitude());
                        gps.setLatitude(gpsAfterConverted.getWgLat());
                        gps.setLongitude(gpsAfterConverted.getWgLon());
                    }
                }
                return mTravelGpsList;
            }
        }
        return null;
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_TRAVEL_DETAIL)) {
            closeLoadingDialog();
        } else if (method.equals(VehicleRequest.METHOD_TRAVEL_ALRAMS)) {
            //mBinding.cover.setVisibility(View.GONE);
        } else if (method.equals(METHOD_TRAVEL_GPS)) {
            if(isAdsorbent) {
                updateAdsorbent();
            }
            //ToastUtil.showToast(this, R.string.vehicle_adsorbent_fail);
            closeLoadingDialog();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(Constant.KEY_TRAVEL, mTravel);
    }

    @Override
    public int onGetWhereHomeTravelHolderIn() {
        return IN_TRAVEL_DETAIL;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (seekBar.getMax() <= 0) {
            return;
        }
        // seekBar页面加载时默认为0触发onProgressChanged，故先屏蔽
        if (mChartHolder.getPlayState() != VehicleTravelSpeedChartHolder.PLAY_STATE_PLAYING) {
            return;
        }
        mCurrentGpsProgress = progress;
        mChartHolder.updateData(progress);
        mMapHolder.updateTravel(progress);
        mChartFullHolder.updateData(progress);
        //mMapFullHolder.updateTravel(progress);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onMapTrailEnd(boolean manual) {

    }

    @Override
    public void onMapTrailDrawing(TravelGps gps) {
        mChartHolder.onDrawingGps(gps);
        mChartFullHolder.onDrawingGps(gps);
    }

    @Override
    public Travel onGetTravelData() {
        return mTravel;
    }

    private Runnable mRunnSeekbarProgress = new Runnable() {
        @Override
        public void run() {
            mCurrentGpsProgress++;
            if (mCurrentGpsProgress >= mTravelGpsResponse.size()) {
                mCurrentGpsProgress = 0;
                mChartHolder.getBinding().sb.setProgress(mCurrentGpsProgress);
                mChartHolder.setPlayState(VehicleTravelSpeedChartHolder.PLAY_STATE_INIT);
                mChartFullHolder.setPlayState(VehicleTravelSpeedChartHolder.PLAY_STATE_INIT);
                mMapHolder.updateTravelEnd();
            } else {
                mChartHolder.getBinding().sb.setProgress(mCurrentGpsProgress);
                mHandler.postDelayed(mRunnSeekbarProgress, DURATION_ONE_GPS);
            }
        }
    };

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.iv_scale) {
            mExpand = !mExpand;
            if (mExpand) {
                /*mBinding.clContentFull.setVisibility(View.VISIBLE);
                mMapHolder.getBinding().ivScale.setVisibility(View.GONE);
                ViewGroup parent = (ViewGroup) mMapHolder.getBinding().clMap.getParent();
                parent.removeView(mMapHolder.getBinding().clMap);
                mBinding.mapContainer.addView(mMapHolder.getBinding().clMap,
                                              new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                                                                           FrameLayout.LayoutParams.MATCH_PARENT));
                *//*mHandler.postDelayed(() -> {
                    mMapHolder.getBinding().bmapView.requestLayout();
                    mMapHolder.getBinding().clMap.requestLayout();
                }, 2000);*//*

                mBinding.clContent.setVisibility(View.INVISIBLE);*/
                mBinding.nsvContent.fling(0);
                mBinding.nsvContent.smoothScrollTo(0, 0);

                mMapHolder.getBinding().ivScale.setVisibility(View.GONE);
                mChartFullHolder.getBinding().getRoot().setVisibility(View.VISIBLE);
                View map = mBinding.map.getRoot();
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) map.getLayoutParams();
                params.leftMargin = 0;
                params.rightMargin = 0;
                params.topMargin = 0;
                Point size = ScreenUtil.getRealSize(this);
                params.dimensionRatio = String.format("%d:%d",
                                                      size.x,
                                                      size.y - mBinding.title.getHeight());
                map.setLayoutParams(params);
                mBinding.title.setTitle(R.string.trail_detail);
                mBinding.nsvContent.setNestedScrollingEnabled(false);
                mBinding.nsvContent.setOnTouchListener(new View.OnTouchListener(){
                    @Override
                    public boolean onTouch(View arg0, MotionEvent arg1) {
                        return true;
                    }
                });
            } else {
                /*mBinding.clContentFull.setVisibility(View.GONE);
                mMapHolder.getBinding().ivScale.setVisibility(View.VISIBLE);
                ViewGroup parent = (ViewGroup) mMapHolder.getBinding().clMap.getParent();
                parent.removeView(mMapHolder.getBinding().clMap);
                mMapHolder.getBinding().cv.addView(mMapHolder.getBinding().clMap);
                *//*mHandler.postDelayed(() -> {
                    mMapHolder.getBinding().bmapView.requestLayout();
                    mMapHolder.getBinding().clMap.requestLayout();
                }, 2000);*//*
                mBinding.clContent.setVisibility(View.VISIBLE);*/
                mMapHolder.getBinding().ivScale.setVisibility(View.VISIBLE);
                mChartFullHolder.getBinding().getRoot().setVisibility(View.INVISIBLE);
                View map = mBinding.map.getRoot();
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) map.getLayoutParams();
                params.leftMargin = ResUtil.getDimension(R.dimen.dp_12);
                params.rightMargin = ResUtil.getDimension(R.dimen.dp_12);
                params.topMargin = ResUtil.getDimension(R.dimen.dp_12);
                params.dimensionRatio = "345:259";
                map.setLayoutParams(params);
                mBinding.title.setTitle(R.string.travel_detail);
                mBinding.nsvContent.setNestedScrollingEnabled(true);
                mBinding.nsvContent.setOnTouchListener(new View.OnTouchListener(){
                    @Override
                    public boolean onTouch(View arg0, MotionEvent arg1) {
                        return false;
                    }
                });
            }
        } else if (vid == R.id.iv_play) {
            if(isAdsorbent) { // 道路吸附开启后，速度趋势图播放按钮不可点击
                return;
            }
            /*if (mMapHolder.isShowingTrail() || mMapFullHolder.isShowingTrail()) {
                return;
            }
            if (mMapHolder.showTrailAnimator()) {
                mChartHolder.updatePlayUi(false);
            }
            if (mMapFullHolder.showTrailAnimator()) {
                mChartFullHolder.updatePlayUi(false);
            }*/
            /*if (mMapHolder.isShowingTrail() || mMapFullHolder.isShowingTrail()) {
                mMapHolder.pauseTrailAnimator();
                mMapFullHolder.pauseTrailAnimator();
                mChartHolder.updatePlayUi(true);
                mChartFullHolder.updatePlayUi(true);
            } else {
                mMapHolder.showTrailAnimator();
                mMapFullHolder.showTrailAnimator();
                mChartHolder.updatePlayUi(false);
                mChartFullHolder.updatePlayUi(false);
            }*/
            if (mChartHolder.getPlayState() == VehicleTravelSpeedChartHolder.PLAY_STATE_PLAYING) {
                mHandler.removeCallbacks(mRunnSeekbarProgress);
                mChartHolder.setPlayState(VehicleTravelSpeedChartHolder.PLAY_STATE_PAUSE);
                mChartFullHolder.setPlayState(VehicleTravelSpeedChartHolder.PLAY_STATE_PAUSE);
            } else {
                mChartHolder.setPlayState(VehicleTravelSpeedChartHolder.PLAY_STATE_PLAYING);
                mChartFullHolder.setPlayState(VehicleTravelSpeedChartHolder.PLAY_STATE_PLAYING);
                mChartHolder.updateData(mCurrentGpsProgress);
                mMapHolder.updateTravel(mCurrentGpsProgress);
                mChartFullHolder.updateData(mCurrentGpsProgress);
                mHandler.postDelayed(mRunnSeekbarProgress, DURATION_ONE_GPS);
            }

        } else if (vid == R.id.iv_adsorbent) {
            updateAdsorbent();
            if(isAdsorbent) {
                if (mTravelGpsResponse_adsorbent != null
                        && mTravelGpsResponse_adsorbent.getData() != null
                        && mTravelGpsResponse_adsorbent.getData().size() > 0) {
                    showLoadingDialog("");
                    timer.schedule(new TimerTask(){
                        public void run(){
                            VehicleTravelDetailActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateGpsDraw(mTravelGpsResponse_adsorbent);
                                    closeLoadingDialog();
                                }
                            });
                        }
                    }, 800);
                } else {
                    showLoadingDialog("");
                    mGeneralManager.getRequestManager()
                            .getVehicleRequest()
                            .getTravelGps(mTravel.getTravelCode(), isAdsorbent ? "1" : "0", this)
                            .execute();
                }
            } else {
                showLoadingDialog("");
                timer.schedule(new TimerTask(){
                    public void run(){
                        VehicleTravelDetailActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateGpsDraw(mTravelGpsResponse);
                                closeLoadingDialog();
                            }
                        });
                    }
                }, 800);
            }
        }
    }

    /**
     * 更新道路吸附开关状态
     */
    private void updateAdsorbent() {
        isAdsorbent = !isAdsorbent;
        if(isAdsorbent) {
            mMapHolder.getBinding().ivAdsorbent.setImageResource(R.drawable.travel_adsorbent_on);
            ColorMatrix colorMatrix = new ColorMatrix();
            colorMatrix.setSaturation(0);
            ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
                    colorMatrix);
            mChartHolder.getBinding().ivPlay.setColorFilter(colorMatrixFilter);
            mChartFullHolder.getBinding().ivPlay.setColorFilter(colorMatrixFilter);
        } else {
            mMapHolder.getBinding().ivAdsorbent.setImageResource(R.drawable.travel_adsorbent_off);
            mChartHolder.getBinding().ivPlay.setColorFilter(null);
            mChartFullHolder.getBinding().ivPlay.setColorFilter(null);
        }
    }

    @Override
    public void onLeftAreaClick() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (mExpand) {
            onClick(mBinding.map.ivScale);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapHolder.onResume();
        //mMapFullHolder.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapHolder.onPause();
        //mMapFullHolder.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(mRunnSeekbarProgress);
        mMapHolder.onDestroy();
        //mMapFullHolder.onDestroy();
        timer.cancel();
        timer = null;
    }


    /*private static class InnerDecoration extends RecyclerView.ItemDecoration {
        private int mSpace14;
        private int mSpace11;

        public InnerDecoration() {
            Context context = XApplication.getInstance();
            mSpace11 = ScreenUtil.dp2px(context, 11);
            mSpace14 = ScreenUtil.dp2px(context, 14);
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect,
                                   @NonNull View view,
                                   @NonNull RecyclerView parent,
                                   @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            int ap = parent.getChildAdapterPosition(view);
            if (ap == RecyclerView.NO_POSITION) {
                return;
            }
            int vt = parent.getAdapter().getItemViewType(ap);
            switch (vt) {
                case VT_TRAVEL_ITEM:
                case VT_TRAVEL_SPEED_CHART:
                case VT_TRAVEL_MAP:
                    outRect.left = mSpace14;
                    outRect.right = mSpace14;
                    outRect.top = mSpace11;
                    break;
                default:
                    break;
            }
        }
    }*/
}
